<script lang="ts">
	import { onMount } from 'svelte';
	import FormItem from './_com/FormItem.svelte';
	import { dataArray } from './page';
	import { alova } from '$utils/request';
	import { createMessage } from '$components/basic/message';
	import { goto } from '$utils/intercept';
	import { validate_controller } from '$utils/validate';

	type OptionItem = {
		id: number;
		name: string;
	};

	let optionsMapper: Record<string, OptionItem[]> = {
		itemCategory: [],
		memberType: []
	};

	onMount(() => {
		const msg = createMessage({ loading: true, message: 'loading configuration', type: 'light' });
		alova
			.Get('/member/select')
			.then((res) => {
				optionsMapper = res as Record<string, OptionItem[]>;

				form['item'] = optionsMapper.itemCategory[0].id;
				form['clienType'] = optionsMapper.memberType[0].id;

				msg.update_loading_to_success('', 0);
			})
			.catch((err) => {
				msg.update_loading_to_error();
			});
	});

	interface FormData {
		username: string; // 用户名
		password: string; // 密码
		confirm: string; // 确认密码
		verify_code: string; // 验证码
		country: number; // 国家Id
		clienType: number; // 会员类型
		allowNote: string; // 是否开启通知

		item: number; // 项目类型
		experience: string; // 经验
		payment: string[];
		freight: string;
		desc: string;
		num: number;
	}

	const getDefault = () =>
		dataArray.reduce((acc, item) => {
			return { ...acc, [item.value]: item.type === 'checkbox' ? [] : '' };
		}, {});

	let form: Partial<FormData> = getDefault(); // form data

	const scrollToBottom = () => {
		const element = document.getElementById('app');
		// console.log(element);
		element?.scrollTo({ behavior: 'smooth', top: element.scrollHeight });
	};

	const sendVerifyCode = async () => {
		try {
			const res = (await alova.Post('/member/send-verify-code', {
				username: form.username,
				type: 1
			})) as API.ResOp;
			if (res.code === 0) createMessage({ message: res.message, type: 'danger' });
			else createMessage({ message: 'verify code send success', type: 'success' });
		} catch (error) {
			createMessage({ message: 'verify code send failed', type: 'danger' });
		}
	};

	const register = () => {
		try {
			const { item, experience, payment, freight, desc, num, ...other } = form;
			const info = { payment, desc, num, freight: Number(freight), experience: Number(experience) };
			info['item'] = optionsMapper.itemCategory.find((i) => i.id === item)?.name;

			const { allowNote, confirm, ...rest } = other;
			const params = { info: JSON.stringify(info), ...rest };
			params['allowNote'] = allowNote?.[0] ? 1 : 0;

			const createAction = (key: string) => () =>
				createMessage({ message: `${key} is required`, type: 'warning' });
			const controller = validate_controller();
			controller
				.put('email', params.username)
				.put('notnull', params.password, createAction('password'))
				.put('notnull', params.verify_code, createAction('verify code'))
				.put(() => Boolean(info.payment!.length), '', createAction('payment method'))
				.put('notnull', info.desc, createAction('description'));

			if (confirm !== params.password) {
				createMessage({ message: 'password not match', type: 'danger' });
				return (form.confirm = ''), (form.password = '');
			}

			if (controller.check()) return;

			alova
				.Post('/member/register', params)
				.then((res) => {
					const { code, message } = res as API.ResOp;
					if (code === 0) createMessage({ message, type: 'danger' });
					else {
						createMessage({ message: 'register success', type: 'success' });
						goto('/login'); // TODO: 跳转到登录页面
					}
				})
				.catch(() => {
					createMessage({ message: 'register failed', type: 'danger' });
				});
		} catch (error) {
			createMessage({ message: 'register failed', type: 'danger' });
		}
	};

	onMount(scrollToBottom);
</script>

<div class="user-account flex-cc flex-col p-20px gap-4px">
	<!-- 账户信息 -->
	<div
		class="userinfo w-1320px max-w-100% min-w-350px flex-cc px-8px"
		style="background-image: linear-gradient(to right, #dbeafe , #dbeafe  50%, transparent 50%);"
	>
		<div id="simple-content" class="w-full p-20px!">
			<form class="w-full grid grid-cols-2 gap-40px">
				<div class="flex flex-col gap-20px">
					{#each dataArray.slice(0, 6) as item}
						<FormItem
							{item}
							bind:form
							bind:options={optionsMapper}
							on:sendVerifyCode={sendVerifyCode}
							on:register={register}
						/>
					{/each}
				</div>
				<div class="flex flex-col gap-20px">
					{#each dataArray.slice(6) as item}
						<FormItem
							{item}
							bind:form
							bind:options={optionsMapper}
							on:sendVerifyCode={sendVerifyCode}
							on:register={register}
						/>
					{/each}
				</div>
			</form>
		</div>
	</div>
</div>
